//
//  ComposeViewController.swift
//  WeiBo_NB
//
//  Created by apple on 15/3/5.
//  Copyright (c) 2015年 Ai. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {

    // 分享新鲜事懒加载
   lazy var placeHolderLabel:UILabel = {
    var l = UILabel()
    l.text = "分享新鲜事..."
    l.font = UIFont.systemFontOfSize(14)
    l.textColor = UIColor.lightGrayColor()
    l.frame = CGRectMake(5, 9, 83, 17)
    l.sizeToFit()
        return l
    }()
    
    /// 发送微博按钮
    @IBOutlet weak var sendButton: UIBarButtonItem!
    // 文本框
    @IBOutlet weak var myTextView: UITextView!
    // toolBar
    @IBOutlet weak var tabbarVerticalHeight: NSLayoutConstraint!
    
    // 点击了表情按钮
    @IBAction func emojClick(sender: UIButton) {
        // 先隐藏系统键盘
        myTextView.resignFirstResponder()

    ///  inputView为空，即为系统键盘
        if myTextView.inputView == nil{
            let sb = UIStoryboard(name: "EmojViewController", bundle: nil)
            let vc = sb.instantiateInitialViewController() as! UIViewController
            myTextView.inputView = vc.view
        }else{
            myTextView.inputView = nil
        }
        // 调出键盘
        myTextView.becomeFirstResponder()
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        // 设置界面
        setupUI()
        
        // 监听通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didTabbarChanged:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didTabbarChanged:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
    // ViewDidLoad之后的一些操作
    func setupUI(){
        // 调出键盘
        myTextView.becomeFirstResponder()
        // 可以上下拉动
        myTextView.alwaysBounceVertical = true
        
        myTextView.addSubview(self.placeHolderLabel)
    }
    
    // 移除监听
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 通知调用方法
    func didTabbarChanged(info:NSNotification){
        
        var duration = (info.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        var height : CGFloat = 0
        if info.name == UIKeyboardWillShowNotification{
            var rect = (info.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
            // 字典中取出来是NSValue对象，需要转化为CGRect,Bar往上移动
            height =  rect.size.height
        }else{
            // Bar往下隐藏
            height = 0
        }
        
        self.tabbarVerticalHeight.constant = height
        // 添加动画
        UIView.animateWithDuration(duration, animations: { () -> Void in
            self.view.layoutIfNeeded()
        })

    }
    
    ///  发送微博
    @IBAction func sendClick(sender: AnyObject) {
        let net = netWorkManager.sharedManager
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        if let token = AccessToken.loadAccessToken()?.access_token{
            let params = ["access_token":token,
                "status":myTextView.text!]
            net.requestJSON(HTTPMethod.POST, urlString, params, completion: { (result, error) -> () in
                SVProgressHUD.showInfoWithStatus("发送成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            })
        }
        
    }
 
    ///  取消发送微博
    @IBAction func cancelClick(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

 

}

// TextView代理方法
extension ComposeViewController: UITextViewDelegate{
    
    ///  当文本开始变化
    func textViewDidChange(textView: UITextView){
        
        textView.becomeFirstResponder()
        
        if !textView.text.isEmpty {
            // 当文字内容不为空时
            sendButton.enabled = true
            self.placeHolderLabel.hidden = true
        }else{
            sendButton.enabled = false
            self.placeHolderLabel.hidden = false
        }
    }
    // 当textView开始滚动时
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        // 键盘退出
        myTextView.resignFirstResponder()
    }
    
    ///  将要replacementText添加到TextView上去的时候会调用
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
            //当前文字长度加上将要加上去的文字的长度大于140时，返回false
        if (textView.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) + text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) > 140{
            
            return false
        }else{
            return true
        }
    }


}
